import { useState } from 'react'
import { NavBar, Icon, WingBlank, InputItem, Button, Toast } from 'antd-mobile'

import { reqRegister } from '../../../api/register'
import { pwdReg } from '../../../utils/regs'
import msg from './msg.png'
import './index.less'

function PasswordRegister({ history, location }) {
  //密码
  const [password, setPassword] = useState('')
  //密码是否明文
  const [isciphertext, setIsCiphertext] = useState(true)
  //下一步按钮是否禁用
  const [disabled, setDisabled] = useState(true)

  //密码改变触发事件
  const handlePasswordChange = (val) => {
    setPassword(val)
    pwdReg.test(val) ? setDisabled(false) : setDisabled(true)
  }

  //密码明文切换
  const passwordShow = () => {
    setIsCiphertext(!isciphertext)
  }

  //注册完成
  const next = async () => {
    try {
      const res = await reqRegister(location.state, password)
      if (res.data.code === 20000) {
        history.push('/', res.data.data.user)
      } else {
        Toast.fail(res.data.message, 2)
      }
    } catch (err) {
      Toast.fail('请求失败...', 2)
    }
  }

  return (
    <div className="verify-password">
      <NavBar
        mode="light"
        icon={<Icon className="icon-left" type="left" />}
        onLeftClick={() => {
          history.goBack()
        }}
      >
        硅谷注册
      </NavBar>
      <WingBlank>
        <img className="verify-code-msg" src={msg} alt="msg" />
        <p className="verify-code-tip">请设置登录密码</p>
        <InputItem
          type={isciphertext ? 'password' : 'text'}
          className="verify-password-btn"
          placeholder="请设置8-20位登录密码"
          value={password}
          onChange={handlePasswordChange}
          extra={
            <span
              className={`iconfont icon-eyes icon-${
                isciphertext ? 'hidecontent' : 'browse'
              }`}
              onTouchEnd={passwordShow}
            ></span>
          }
        />
        <p className="verify-password-text">
          密码由8-20位字母、数字或半角符号组成，不能是10位以下纯数字/字母/半角符号，字母需区分大小写
        </p>
        <Button
          type="primary"
          disabled={disabled}
          className="btn"
          onClick={next}
        >
          下一步
        </Button>
        <span className="verify-code-question">
          遇到问题?请<span>联系客服</span>
        </span>
      </WingBlank>
    </div>
  )
}

export default PasswordRegister
